import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:provider/provider.dart';
import '../../providers/user_provider.dart';
import '../../utils/G.dart';
import '../../providers/comment_provider.dart';

class OrderComment extends StatefulWidget {
  const OrderComment({Key? key}) : super(key: key);

  @override
  _OrderCommentState createState() => _OrderCommentState();
}

class _OrderCommentState extends State<OrderComment> {
  Map item = {};
  double product_score = 0; // 商品质量评分
  double service_score = 0; // 服务态度评分
  String comment = "";

  @override
  Widget build(BuildContext context) {
    item = Provider.of<CommentProvider>(context).product;

    return Scaffold(
      appBar: AppBar(
        title: const Text('评论商品'),
        centerTitle: true,
      ),
      body: Container(
        margin: const EdgeInsets.all(10),
        child: Column(
          children: [
            // 商品信息
            _renderProductInfo(),

            // 五星评分
            _renderRatingBar(),

            // 评论内容
            _renderComment(),

            // 提交按钮
            _renderSubmit()
          ],
        ),
      ),
    );
  }

  Widget _renderProductInfo() {
    return Container(
        margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
        color: Colors.white,
        child: ListTile(
          isThreeLine: true,
          onTap: () {
            Map<String, dynamic> p = {'id': item['product_id']};
            G.router.navigateTo(
                context, '/product_detail' + G.parseQuery(params: p));
          },
          leading: G.imageWidget(item['productInfo']['image'],
              width: 100, height: 100),
          title: Text(
            item['productInfo']['store_name'].toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
            overflow: TextOverflow.ellipsis,
          ),
          subtitle: Column(
            children: [
              Container(
                width: 200,
                child: Text(
                  item['productInfo']['attrInfo']['sku'],
                  style: const TextStyle(
                    fontSize: 16,
                  ),
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.left,
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "￥ " +
                        item['truePrice'].toString() +
                        " X " +
                        item['cart_num'].toString(),
                    style: TextStyle(
                        fontSize: 16,
                        color: Theme.of(context).primaryColor,
                        fontWeight: FontWeight.w500),
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              )
            ],
          ),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
              side: BorderSide(color: Colors.grey.shade400, width: 1)),
        ));
  }

  Widget _renderRatingBar() {
    return Column(
      children: [
        ListTile(
          title: const Text('商品质量'),
          trailing: RatingBar.builder(
            initialRating: product_score,
            itemSize: 24,
            minRating: 1,
            direction: Axis.horizontal,
            allowHalfRating: true,
            itemCount: 5,
            itemPadding: const EdgeInsets.symmetric(horizontal: 1.0),
            itemBuilder: (context, _) => const Icon(
              Icons.star,
              color: Colors.amber,
            ),
            // ignoreGestures: true, // 忽略手势操作
            onRatingUpdate: (rating) {
              // print(rating);
              product_score = rating;
            },
          ),
        ),
        ListTile(
          title: const Text('服务态度'),
          trailing: RatingBar.builder(
            initialRating: service_score,
            itemSize: 24,
            minRating: 1,
            direction: Axis.horizontal,
            allowHalfRating: true,
            itemCount: 5,
            itemPadding: const EdgeInsets.symmetric(horizontal: 1.0),
            itemBuilder: (context, _) => const Icon(
              Icons.star,
              color: Colors.amber,
            ),
            // ignoreGestures: true, // 忽略手势操作
            onRatingUpdate: (rating) {
              // print(rating);
              service_score = rating;
            },
          ),
        ),
      ],
    );
  }

  Widget _renderComment() {
    return Container(
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
          border: Border.all(width: 1, color: Colors.grey.shade300)),
      child: TextField(
          autofocus: false,
          keyboardType: TextInputType.text,
          maxLines: 5,
          textAlign: TextAlign.left,
          textDirection: TextDirection.ltr,
          decoration: const InputDecoration(
              isCollapsed: true,
              border: InputBorder.none,
              hintText: "说说你的看法",
              hintStyle: TextStyle(fontSize: 16)),
          onChanged: (value) {
            // print(value);
            comment = value;
          }),
    );
  }

  Widget _renderSubmit() {
    return ElevatedButton(
        onPressed: () async {
          // 提交表单，执行评论添加（调用添加评论接口）
          if (Provider.of<UserProvider>(context, listen: false).isLogin) {
            var res = await G.api.order.comment(
                unique: item['unique'],
                comment: comment,
                product_score: product_score,
                service_score: service_score);
            if (res['status'] == 200) {
              Map<String, dynamic> p = {'id': item['product_id']};
              G.router.navigateTo(
                  context, '/product_detail' + G.parseQuery(params: p));
            } else {
              G.error('添加评论失败');
            }
          } else {
            G.router.navigateTo(context, '/login');
          }
        },
        child: const Text('提交'),
        style: ButtonStyle(
            padding: MaterialStateProperty.all(const EdgeInsets.all(10)),
            minimumSize: MaterialStateProperty.all(Size(G.width - 40, 50))));
  }
}
